﻿using AutoMapper;
using B.S.BaseData.Domain.LogTable;
using B.S.BaseData.Domain.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Domain.Interfaces;
using B.S.BaseData.ReadAPI.Applications.Commands.Users;
using B.S.BaseData.WriteAPI.Applications.Commands.Users;
using B.S.BaseData.WriteAPI.DTOs.ResponseDto;
using MediatR;

namespace B.S.BaseData.WriteAPI.Applications.CommandHandler.Users
{
	public class UserPhoneLoginCommandHandler : IRequestHandler<UserPhoneLoginCommand, ApiResult<UserDTO>>
	{
		IBaseRepository<UserInfo> userRep;
		IBaseRepository<Role> roleRep;
		IBaseRepository<UserRole> userRoleRep;
		IBaseRepository<LoginLog> loginLogRep;
		IMapper mapper;

		public UserPhoneLoginCommandHandler(IBaseRepository<UserInfo> userRep, IBaseRepository<Role> roleRep, IMapper mapper, IBaseRepository<UserRole> userRoleRep, IBaseRepository<LoginLog> loginLogRep)
		{
			this.userRep = userRep;
			this.roleRep = roleRep;
			this.mapper = mapper;
			this.userRoleRep = userRoleRep;
			this.loginLogRep = loginLogRep;
		}

		public async Task<ApiResult<UserDTO>> Handle(UserPhoneLoginCommand request, CancellationToken cancellationToken)
		{
			try
			{
				var user = await userRep.GetAsync(x => x.Phone==request.Phone);
				if (user == null) return ApiResult<UserDTO>.Fail("用户不存在", StatusCodeEnum.UserNotExist);


				var userRole = await userRoleRep.GetAsync(x => x.UserId == user.UserId);
				var role = await roleRep.GetAsync(x => x.RoleId == userRole.RoleId);
				var userdto = mapper.Map<UserDTO>(user);
				userdto.RoleName = role.RoleName;
				//实例化日志表
				LoginLog loginlog = new LoginLog();
				//添加日志
				loginlog.LogId = Guid.NewGuid().ToString();
				loginlog.UserId = user.UserId;
				loginlog.LoginTime = DateTime.Now;
				//完成日志添加
				await loginLogRep.InsertAsync(loginlog);

				return ApiResult<UserDTO>.Success(userdto, StatusCodeEnum.Ok);
			}
			catch (Exception)
			{

				throw;
			}
		}
	}
}
